package com.yuyou.train.user.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.train.service.api.lesson.entity.Lesson;
import com.yuyou.train.service.api.lesson.entity.LessonClass;
import com.yuyou.train.service.api.lesson.entity.LessonResourceRuleRelation;
import com.yuyou.train.service.api.lesson.entity.Rule;
import com.yuyou.train.service.api.lesson.service.LessonAPI;
import com.yuyou.train.service.api.lesson.service.ResourceAPI;
import com.yuyou.train.service.api.lesson.service.RuleAPI;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.entity.UserDynamic;
import com.yuyou.train.service.api.user.entity.UserHw;
import com.yuyou.train.service.api.user.entity.UserHwBe;
import com.yuyou.train.service.api.user.entity.UserHwTeacher;
import com.yuyou.train.service.api.user.entity.UserLessonProgress;
import com.yuyou.train.service.api.user.entity.UserPraise;
import com.yuyou.train.service.api.user.entity.UserRemind;
import com.yuyou.train.user.mapper.UserHwMapper;
import com.yuyou.train.user.service.IUserDataConfigService;
import com.yuyou.train.user.service.IUserDynamicService;
import com.yuyou.train.user.service.IUserHwBeService;
import com.yuyou.train.user.service.IUserHwPraiseService;
import com.yuyou.train.user.service.IUserHwService;
import com.yuyou.train.user.service.IUserHwTeacherService;
import com.yuyou.train.user.service.IUserLessonProgressBehaService;
import com.yuyou.train.user.service.IUserLessonProgressService;
import com.yuyou.train.user.service.IUserPraiseService;
import com.yuyou.train.user.service.IUserRemindService;
import com.yuyou.train.user.service.IUserService;
import com.yuyou.train.user.service.IUserTotalService;
import com.yuyou.train.user.vo.req.ReqUserHwCorrect;
import com.yuyou.train.user.vo.req.ReqUserHwCorrectConfig;
import com.yuyou.train.user.vo.resp.RespGetLessonUserInfo;
import com.yuyou.train.user.vo.resp.RespUserHw;
import com.yuyou.train.user.vo.resp.RespUserHwBeConfig;
import com.yuyou.train.util.bean.Pagination;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.constant.user.UserMarkCons;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.lesson.LessonEnums;
import com.yuyou.train.util.enums.user.UserDynamicEnums;
import com.yuyou.train.util.enums.user.UserEnums;
import com.yuyou.train.util.enums.user.UserHwEnums;
import com.yuyou.train.util.enums.user.UserLessonProgressEnums;
import com.yuyou.train.util.enums.user.UserPraiseEnums;
import com.yuyou.train.util.enums.user.UserRemindEnums;
import com.yuyou.train.util.message.CommMess;
import com.yuyou.train.util.message.lesson.LessonMess;
import com.yuyou.train.util.message.user.UserDynamicMess;
import com.yuyou.train.util.message.user.UserLessonProMess;
import com.yuyou.train.util.message.user.UserRemindMess;
import com.yuyou.train.util.tool.DefindBeanUtils;
import com.yuyou.train.util.tool.MathUtils;
import com.yuyou.train.util.tool.Sequence;

@Service
public class UserHwServiceImpl implements IUserHwService{

	@Autowired
	private UserHwMapper userHwMapper;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IUserHwBeService userHwBeService;
	
	@Autowired
	private LessonAPI lessonAPI;
	
	@Autowired
	private ResourceAPI resourceAPI;
	
	@Autowired
	private RuleAPI ruleAPI;
	
	@Autowired
	private IUserLessonProgressService userLessonProgressService;
	
	@Autowired
	private IUserHwTeacherService userHwTeacherService;
	
	@Autowired
	private IUserHwPraiseService userHwPraiseService;
	
	@Autowired
	private IUserLessonProgressBehaService userLessonProgressBehaService;
	
	@Autowired
	private IUserRemindService userRemindService;
	
	@Autowired
	private IUserDynamicService userDynamicService;
	
	@Autowired
	private IUserTotalService userTotalService;
	
	@Autowired
	private IUserDataConfigService userDataConfigService;
	
	@Autowired
	private IUserPraiseService userPraiseService;
	
	@Override
	public int deleteByPrimaryKey(String id) {
		return userHwMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(UserHw record) {
		record.setId(Sequence.getSequence().getNextId());
		record.setCreateTime(new Date());
		return userHwMapper.insert(record);
	}

	@Override
	public UserHw selectByPrimaryKey(String id) {
		return userHwMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(UserHw record) {
		record.setUpdateTime(new Date());
		return userHwMapper.updateByPrimaryKeySelective(record);
	}

	public ResBoolSimpleInfo<String> addUserHw(UserHw record) {
		this.insert(record);
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public int finishUserHw(UserHw record) {
		record.setStatus(UserHwEnums.hwStatus.pass.getValue());
		return this.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<UserHw> findUserHwPageList(Pagination<UserHw> p) {
		return userHwMapper.findUserHwPageList(p);
	}

	@Override
	public int findUserHwPageCount(Pagination<UserHw> p) {
		return userHwMapper.findUserHwPageCount(p);
	}

	@Override
	public List<UserHw> findUserHw(UserHw userHw) {
		return userHwMapper.findUserHw(userHw);
	}

	@Override
	public UserHw selectUserHwByStatus(String userId,String lessonId,String status) {
		return userHwMapper.selectUserHwByStatus(userId,lessonId,status);
	}

	@Override
	public ResBoolSimpleInfo<RespUserHw> hwDetail(String id,String teacherId) {
		ResBoolSimpleInfo<RespUserHw> res=new ResBoolSimpleInfo<RespUserHw>();
		
		RespUserHw respHw=new RespUserHw();
		UserHw userHw=this.selectByPrimaryKey(id);
				
		DefindBeanUtils.copyProperties(userHw, respHw);
		respHw.setUserHwId(id);
		respHw.setUserFileUrl(userHw.getUserAttachUrl());
		respHw.setUserFileName(userHw.getUserAttachName());
		respHw.setFileSourceName(userHw.getFileSourceName());
				
		//作业学员信息
		User user=userService.selectByPrimaryKey(userHw.getUserId());
		RespGetLessonUserInfo userInfo=new RespGetLessonUserInfo();
		DefindBeanUtils.copyProperties(user, userInfo);
		List<String> tags=userDataConfigService.findDataNameByUserIdAndType(user.getId(), UserEnums.userDataConfigType.tag.getValue());
		userInfo.setTags(tags);
		respHw.setUserInfo(userInfo);	
		respHw.setUserName(user.getUsername());
		
		//是否学员的老师进来		
		if(user.getParentId().equals(teacherId)){
			respHw.setUserTeacher(true);
		}

		Lesson lesson=lessonAPI.selectLessonById(userHw.getLessionId());
		//判断课程有没有删除
		if(!lesson.isDel()){
			LessonResourceRuleRelation lesResoRulRel=lessonAPI.selectLessonRelByLessonId(lesson.getId());	
			if(lesResoRulRel==null){
				//该课程没有配资源
				res.setSuccess(false);
				res.setMessage(LessonMess.ERR_LESSON_RESOURCE_EMPTY);
				return res;
			}
			Rule rule=ruleAPI.selectById(lesResoRulRel.getRuleId());
			if((rule.getNeedScore()!=null&&rule.getNeedScore()>=0)){
				respHw.setNeedTeacher(true);
			}else{
				respHw.setNeedTeacher(false);
			}			 
			respHw.setLessonName(lesson.getName());			
			LessonClass _class=lessonAPI.findLessonClassById(user.getClassId());
			respHw.setClassName(_class.getName());
			
		}else{
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_END_LESSON_LOST);
			return res;
		}				
		UserHwTeacher userHwTeacher=userHwTeacherService.selectByHwAndUserId(id, teacherId);
		if(userHwTeacher==null){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_POWER);
			return res;
		}
				
		respHw.setTeachAttachName(userHwTeacher.getTeachAttachName());
		respHw.setTeachAttachUrl(userHwTeacher.getTeachAttachUrl());
		respHw.setTeachFileSourceName(userHwTeacher.getFileSourceName());
		respHw.setContent(userHwTeacher.getContent());
		
		respHw.setTeacherhasDo(userHwTeacher.getStatus().equals("1")?true:false);
		
		List<UserHwTeacher> mustList=userHwTeacherService.findByHw(userHw.getId(), null);
		List<UserHwTeacher> hasList=userHwTeacherService.findByHw(userHw.getId(), "1");
		
		respHw.setMustTeaNum(mustList.size());
		respHw.setHasTeaNum(hasList.size());
		
		respHw.setScore(userHw.getScore());
		respHw.setTeachScore(userHwTeacher.getScore());
		
		
		 //总共多少赞
		 Long goodNum =userPraiseService.sumByForeignId(userHw.getId(),UserPraiseEnums.isPraise.yes.getValue());
		 respHw.setGood(goodNum==null?0:goodNum);
		 
		 UserPraise isMyGood=userPraiseService.selectUserPraise(userHw.getId(), teacherId, CommEnums.resourceType.hwNeedComment.getValue(), UserPraiseEnums.isPraise.yes.getValue());
		 respHw.setIsMyGood(isMyGood==null?false:true);
		 
		if(userHw.getResourceType().equals(CommEnums.resourceType.hwNeedComment.getValue())){
								
			List<RespUserHwBeConfig> configList=userHwMapper.findUserConfigList(userHwTeacher.getId());
			//树形结构
			configList=toTreeDTO(configList, null);						
			respHw.setConfigList(configList);
			
			//学生的点赞不需要？只显示老师？
			//学员导师才有赞踩
			List<String> goodList=new ArrayList<String>();
			List<String> badList=new ArrayList<String>();
			if(user.getParentId().equals(teacherId)){
				goodList=userHwPraiseService.findUserHwPraiseStr(userHw.getId(),UserHwEnums.hwType.teacher.getValue(), UserHwEnums.HwPraiseType.praise.getValue());				
				badList=userHwPraiseService.findUserHwPraiseStr(userHw.getId(),UserHwEnums.hwType.teacher.getValue(), UserHwEnums.HwPraiseType.tread.getValue());
				
			}
			respHw.setBadList(badList);
			respHw.setGoodList(goodList);

		}	
		res.setData(respHw);
		res.setSuccess(true);
		
		return res;
	}

	private List<RespUserHwBeConfig> toTreeDTO(List<RespUserHwBeConfig> treeList , String parentId){
		// 返回DTO
		List<RespUserHwBeConfig> lessonTreeListRet = new ArrayList<>();
		for(RespUserHwBeConfig dto : treeList){
			if(dto.getParentId() == parentId || (dto.getParentId() !=null && dto.getParentId().equals(parentId))){
				lessonTreeListRet.add(dto);
				List<RespUserHwBeConfig> children = toTreeDTO(treeList, dto.getUserHwBeConfigId());
				dto.setChildren(children);
			}
		}

		return lessonTreeListRet;
	}
	
	
	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<String> correctHw(ReqUserHwCorrect reqUserHwCorrect,String teacherId) throws Exception {
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();	
		UserHw userHw=this.selectByPrimaryKey(reqUserHwCorrect.getUserHwId());
		//作业学员
		User user=userService.selectByPrimaryKey(userHw.getUserId());	
		String subjectId=userDataConfigService.selectUserSubjectId(user.getId());		
		Lesson lesson=lessonAPI.selectLessonById(userHw.getLessionId());
		
		ResBoolSimpleInfo<String> val=ReqUserHwCorrect.validate(reqUserHwCorrect, userHw.getResourceType(),user.getParentId().equals(teacherId));
		if(!val.isSuccess()){
			res.setSuccess(false);
			res.setMessage(val.getMessage());
			return res;
		}
		

		
		//当前班级为禁用中，不能过关
		LessonClass _class=lessonAPI.findLessonClassById(user.getClassId());
		if(_class.getIsUse().equals(CommEnums.isUse.no.getValue())){
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_LESSON_CLASS_DISABLE);
			return res;
		}
		
		//课程已删除直接返回
		if(lesson.isDel()){
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_END_LESSON_LOST);
			return res;
		}
		
		
		LessonResourceRuleRelation rel= lessonAPI.selectLessonRelByLessonId(userHw.getLessionId());		
		//一个课程只有一个资源只有一个规则
		Rule rule=ruleAPI.selectById(rel.getRuleId());	
		
		//学员的当前课程
		UserLessonProgress progress=userLessonProgressService.getUserCurrLesson(user.getId(),user.getClassId());
		
		UserHwTeacher userHwTeacher=userHwTeacherService.selectByHwAndUserId(reqUserHwCorrect.getUserHwId(), teacherId);
		if(userHwTeacher==null){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_POWER);
			return res;
		}
		
		
		if(userHwTeacher.getStatus().equals("1")){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_REAPET);
			return res;
		}
		
		//防重复操作
		if(!progress.getLessonId().equals(userHw.getLessionId())){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_REAPET);
			return res;
		}
		
		
		if(userHw.getResourceType().equals(CommEnums.resourceType.hwJustCommit.getValue())){	
			//提交型作业			
			if(!user.getParentId().equals(teacherId)){
				res.setSuccess(false);
				res.setMessage(CommMess.ERR_POWER);
				return res;
			}
			
			
			userHwTeacher.setContent(reqUserHwCorrect.getContent());
			userHwTeacher.setScore(reqUserHwCorrect.getScore());
			userHwTeacher.setTeachAttachName(reqUserHwCorrect.getTeachAttachName());
			userHwTeacher.setTeachAttachUrl(reqUserHwCorrect.getTeachAttachUrl());
			userHwTeacher.setFileSourceName(reqUserHwCorrect.getFileSourceName());

			//判断是否过关	
			if(reqUserHwCorrect.getScore()>=rule.getNeedScore()){
				userHw.setStatus(UserHwEnums.hwStatus.pass.getValue());	
				userHw.setScore(userHwTeacher.getScore());
				//更新当前进度状态
				progress.setStatus(UserLessonProgressEnums.status.finish.getValue());	
				
				//统计用户数据
				userTotalService.updateLessonTotal(user, lesson);
				
				userLessonProgressService.openUserNextLessonLock(user.getId(), subjectId, null, true);
//				userLessonProgressService.insertUserNextLesson(user,null);
				//添加积分
				userLessonProgressBehaService.addLessonPoints(user.getId(),lesson);
				//增加课程动态
				userDynamicService.addUserDynamic(new UserDynamic(user.getId(),user.getClassId(),userHw.getLessionId(),
						userHw.getId(),String.format(UserDynamicMess.CONTENT, user.getUsername(),lesson.getName()),UserDynamicEnums.type.homework.getValue(),userHw.getResourceType()));			
			}else{
				userHw.setStatus(UserHwEnums.hwStatus.notPass.getValue());
				userHw.setScore(userHwTeacher.getScore());
				progress.setStatus(UserLessonProgressEnums.status.studying.getValue());
			}	
			
			//统计用户数据
			userTotalService.updateHw80Total(user.getId(), reqUserHwCorrect.getScore());
			
			userLessonProgressService.updateByPrimaryKeySelective(progress);
			userHwTeacher.setStatus("1");
			userHwTeacherService.updateByPrimaryKeySelective(userHwTeacher);
			this.updateByPrimaryKeySelective(userHw);
			
			addRemind(user.getParentId(),userHw);
			
		}else{				
			//自评型作业
			
			//非考核绩点作业权限判断
			if(lesson.getAttr().equals(LessonEnums.attr.comm.getValue()) && !user.getParentId().equals(teacherId)){
				res.setSuccess(false);
				res.setMessage(CommMess.ERR_POWER);
				return res;
			}
			
			//学员导师才有赞踩
			if(user.getParentId().equals(teacherId)){
				userHwPraiseService.addHwPraiseList(reqUserHwCorrect.getGoodList(), reqUserHwCorrect.getUserHwId(), UserHwEnums.hwType.teacher.getValue(), UserHwEnums.HwPraiseType.praise.getValue());
				userHwPraiseService.addHwPraiseList(reqUserHwCorrect.getBadList(), reqUserHwCorrect.getUserHwId(), UserHwEnums.hwType.teacher.getValue(), UserHwEnums.HwPraiseType.tread.getValue());

			}
			
			List<ReqUserHwCorrectConfig> configList=reqUserHwCorrect.getConfigList();
			userHwBeService.delByTeacherId(userHwTeacher.getId());
			for(ReqUserHwCorrectConfig c:configList){
				UserHwBe userHwBe=new UserHwBe();
				userHwBe.setIsOrNot(c.getIsOrNot());
				userHwBe.setUserHwTeacherId(userHwTeacher.getId());
				userHwBe.setUserHwBeConfigId(c.getUserHwBeConfigId());
				userHwBeService.addHwBe(userHwBe);
			}	
			
			//算我的23项评分表总分
			userHwTeacher.setScore(countMy23Score(userHwTeacher.getId()));
			userHwTeacher.setStatus("1");
			userHwTeacherService.updateByPrimaryKeySelective(userHwTeacher);
					
			
			int all23=countAll23Score(userHw.getId());
			//平均分
			userHw.setScore(all23);
			
			//判断是否过关
			boolean isAllTeacherCorrect=isAllTeacherCorrect(userHw.getId());
			if(isAllTeacherCorrect){				
										
					if(all23>=rule.getNeedScore()){
						userHw.setStatus(UserHwEnums.hwStatus.pass.getValue());		
						userHw.setScore(all23);
						//更新当前进度状态
						progress.setStatus(UserLessonProgressEnums.status.finish.getValue());

						//假如是考核节点，要算绩点
						if(lesson.getAttr().equals(LessonEnums.attr.check.getValue())){
							int mul=UserMarkCons.getMultiple1(all23);
							//查出配置绩点
							Lesson pLesson=lessonAPI.selectLessonById(lesson.getParentId());							
							int getMark=pLesson.getMark()*mul;
							progress.setGetMark((double)getMark);
							progress.setMarkCon((double)pLesson.getMark());
						}					
						//积分
						progress.setGetPoints(lesson.getScore());
						//添加积分
						userLessonProgressBehaService.addLessonPoints(user.getId(),lesson);	
						
						//统计用户数据
						userTotalService.updateLessonTotal(user, lesson);
						
						userLessonProgressService.openUserNextLesson(user.getId(), subjectId, null, true);
//						userLessonProgressService.insertUserNextLesson(user,null);						
						userDynamicService.addUserDynamic(new UserDynamic(user.getId(),user.getClassId(),userHw.getLessionId(),
								userHw.getId(),String.format(UserDynamicMess.CONTENT, user.getUsername(),lesson.getName()),UserDynamicEnums.type.homework.getValue(),userHw.getResourceType()));					

					}else{
						userHw.setScore(all23);
						userHw.setStatus(UserHwEnums.hwStatus.notPass.getValue());
						progress.setStatus(UserLessonProgressEnums.status.studying.getValue());
					}						
				
				//统计用户数据
				userTotalService.updateHw80Total(user.getId(), all23);
					
				userLessonProgressService.updateByPrimaryKeySelective(progress);
				
				addRemind(user.getParentId(),userHw);
				
			}						
			this.updateByPrimaryKeySelective(userHw);	
		}
		

		
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	
	
	public static void main(String[] args) {

			int mul=UserMarkCons.getMultiple1(0);
							
			int getMark=8*mul;
			System.out.println((double)getMark);
			System.out.println((double)8);

	} 
	
	
	private void addRemind(String teacherId,UserHw userHw) {
		//添加提醒
		User teacher=userService.selectByPrimaryKey(teacherId);		
		UserRemind userRemind=new UserRemind();
		userRemind.setForeignId(userHw.getId());
		userRemind.setContent(String.format(UserRemindMess.CONTENT, userHw.getUserAttachName(),teacher.getUsername() ));
		userRemind.setSendUserId(teacherId);
		userRemind.setReceUserId(userHw.getUserId());
		userRemind.setType(UserRemindEnums.type.hw.getValue());
		userRemind.setStatus(UserRemindEnums.status.init.getValue());
		userRemind.setLessonId(userHw.getLessionId());
		userRemindService.addRemind(userRemind);

	}
	
	private Integer countMy23Score(String userHwTeacherId){
		List<UserHwBe> list=userHwBeService.findByUserHwTeacherId(userHwTeacherId);
		int yesNum=0;
		for(UserHwBe be:list){
			if(be.getIsOrNot().equals(CommEnums.isOrNot.yes.getValue())){
				yesNum++;
			}
		}
		yesNum=(int)MathUtils.mul(MathUtils.div(yesNum,23,2), 100);
		return yesNum;
	}
	
	private Integer countAll23Score(String hwId){		
		List<UserHwTeacher> list=userHwTeacherService.findByHw(hwId, "1");	
		int sum=0;
		for(UserHwTeacher teacherUw:list){	
			sum+=teacherUw.getScore();
		}			
		sum=(int)MathUtils.div(sum,list.size(),2);	
		return sum;
	}
	
	
	private boolean isAllTeacherCorrect(String hwId){		
		List<UserHwTeacher> list=userHwTeacherService.findByHw(hwId, "0");
		if(list.size()>0){
			return false;
		}else{
			return true;
		}
	}

	@Override
	public UserHw selectOnlyUserHwLock(String userId, String lessonId) {
		return userHwMapper.selectOnlyUserHwLock(userId, lessonId);
	}	

}